import functools
import time
import json
from typing import Any, Callable
import logging

logger = logging.getLogger(__name__)

def log_operation(module: str):
    """
    操作日志装饰器
    
    Args:
        module: 模块名称
    """
    def decorator(func: Callable) -> Callable:
        @functools.wraps(func)
        async def wrapper(*args, **kwargs):
            start_time = time.time()
            # 获取类名（如果是类方法）
            class_name = args[0].__class__.__name__ if args and hasattr(args[0], '__class__') else ''
            func_name = f"{class_name}.{func.__name__}" if class_name else func.__name__
            
            # 记录开始执行的日志
            logger.info(f"开始执行 [{module}.{func_name}]")
            
            # 记录详细的请求信息
            try:
                # 过滤掉self参数，并格式化参数值
                request_params = {
                    'args': [str(arg) for arg in (args[1:] if class_name else args)],
                    'kwargs': {k: str(v) for k, v in kwargs.items()}
                }
                logger.info(f"请求参数: {json.dumps(request_params, ensure_ascii=False)}")
            except Exception as e:
                logger.info(f"参数记录失败: {str(e)}")
            
            try:
                # 执行原函数
                result = await func(*args, **kwargs)
                
                # 记录执行时间和响应结果
                execution_time = time.time() - start_time
                
                logger.info(
                    f"执行完成 [{module}.{func_name}] - "
                    f"耗时: {execution_time:.2f}s - "
                    f"结果: {str(result)}"
                )
                
                return result
                
            except Exception as e:
                # 记录详细的异常信息
                execution_time = time.time() - start_time
                logger.error(
                    f"执行失败 [{module}.{func_name}] - "
                    f"耗时: {execution_time:.2f}s - "
                    f"错误: {str(e)}"
                )
                raise
                
        return wrapper
    return decorator 